package demo.IOInputOutput;

import java.io.*;
import java.util.Arrays;

/**
 * @Auther: hjy(lc))
 * @Date: 2022/8/12-08-12-14:35
 * @Description：demo.IOInputOutput
 */
/*
PrintWriter 和PrintStream 可以同时书写字符和字节
解决中文乱码问题
    （字节读字符）
        方式1-3
    （编码和解码的码不一致）
 */
public class CodeProblem {
    public static void main(String[] args) {
        String str = "中国";
        byte[] bytes = str.getBytes();          //[-28, -72, -83, -27, -101, -67]    UTF-8编码中，一个中文占3个字节
        System.out.println(Arrays.toString(bytes));
        try {
            System.out.println(Arrays.toString(str.getBytes("gbk")));     //[-42, -48, -71, -6]       gbk编码中，一个中文占2个字节
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        //方式一
        PrintWriter pw = new PrintWriter(System.out);
        pw.print("中国");
        pw.close();

        //方式二
        //字节流转为字符流
        OutputStreamWriter osw = new OutputStreamWriter(System.out);
        try {
            osw.write("中国");
            osw.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

        //方式三
        byte[] b = {1,3,4,2,4};
        for (int i = 0; i < b.length; i++) {
            //写字节
            System.out.write(b[i]);
            //写字符
            System.out.println((char)b[i]);
        }
        System.out.flush();

        //解码和编码方式不一致
        BufferedReader br = null;
        try {
            //确保编码方式和解码方式
            //将字节流转为字符流，并指定编码
            InputStreamReader isr = new InputStreamReader(new FileInputStream("a.txt"),"utf-8");
            br = new BufferedReader(isr);
            //br = new BufferedReader(new FileReader("a.txt"));
            String line = null;
            while((line = br.readLine())!= null){
                System.out.println(line);
            }
            System.out.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                if(br != null){
                    br.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
